package me.zhengjie.modules.serviceprovider.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.common.service.TRegionService;
import me.zhengjie.modules.common.service.dto.TRegionQueryCriteria;
import me.zhengjie.modules.equipment.service.TEqpttypeService;
import me.zhengjie.modules.equipment.service.dto.TEqpttypeQueryCriteria;
import me.zhengjie.modules.monitor.service.RedisService;
import me.zhengjie.modules.security.security.AuthenticationInfoEx;
import me.zhengjie.modules.security.security.AuthorizationUser;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.modules.security.utils.JwtTokenUtil;
import me.zhengjie.modules.security.utils.VerifyCodeUtils;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderInfo;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderManager;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderPerson;
import me.zhengjie.modules.serviceprovider.service.*;
import me.zhengjie.modules.serviceprovider.service.dto.*;
import me.zhengjie.modules.system.common.EnumAuditStatus;
import me.zhengjie.modules.system.common.EnumWorkorderStatus;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.DictService;
import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria;
import me.zhengjie.modules.workorder.domain.TTasks;
import me.zhengjie.modules.workorder.service.TWorkOrderLogService;
import me.zhengjie.modules.workorder.service.TWorkOrderService;
import me.zhengjie.modules.workorder.service.dto.TWorkOrderLogQueryCriteria;
import me.zhengjie.modules.workorder.service.dto.TWorkOrderQueryCriteria;
import me.zhengjie.modules.workorder.service.dto.TWorkOrderQueryCriteriaEx;
import me.zhengjie.service.PictureService;
import me.zhengjie.service.SmsSerivice;
import me.zhengjie.utils.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;


/**
* @author xuyukun
* @date 2019-07-20
*/
@RestController
@RequestMapping("api/servicemanager")
public class TServiceproviderManagerController {

    @Autowired
    private TServiceproviderManagerService tServiceproviderManagerService;

    @Autowired
    private RedisService redisService;

    @Autowired
    @Qualifier("jwtServiceManagerUserDetailsService")
    private UserDetailsService userDetailsService;


    @Autowired
    private TServiceproviderInfoService tServiceproviderInfoService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private SmsSerivice smsSerivice;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Autowired
    private PictureService pictureService;

    @Autowired
    private TWorkOrderService tWorkOrderService;

    @Autowired
    private TWorkOrderLogService tWorkOrderLogService;

    @Autowired
    private TServiceproviderContractService tServiceproviderContractService;

    @Autowired
    private TServiceproviderPersonService tServiceproviderPersonService;

    @Autowired
    private DictService dictService;

    @Autowired
    private DictDetailService dictDetailService;

    @Autowired
    private TEqpttypeService tEqpttypeService;

    @Autowired
    private TRegionService tRegionService;

    @Log("获取企业客户TServiceproviderManager")
    @GetMapping(value = "/listManager")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_CREATE')")
    public ResponseEntity query(TServiceproviderManagerQueryCriteria criteria, Pageable pageable) {
        Long id = SecurityUtils.getOwnerId();
        criteria.setServiceproviderId(id);
        return new ResponseEntity(tServiceproviderManagerService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("获取企业对应的工程师TServiceproviderManager")
    @GetMapping(value = "/listEngineer")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_CREATE')")
    public ResponseEntity queryEngineer(TServiceproviderPersonQueryCriteria criteria, Pageable pageable) {
        Long id = SecurityUtils.getOwnerId() ; //服务商id
        criteria.setServiceproviderId(id);
        criteria.setIsDelete(0L); //未删除
        return new ResponseEntity(tServiceproviderPersonService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("注册企业客户TServiceproviderManager")
    @PostMapping(value = "/register")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_CREATE')")
    public ResponseEntity register(@RequestBody JSONObject resources) {
        return new ResponseEntity(tServiceproviderManagerService.register(resources), HttpStatus.CREATED);
    }

    @Log("修改企业用户密码TServiceproviderManager")
    @PostMapping(value = "/resetpassword")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_CREATE')")
    public ResponseEntity resetpassword(@RequestBody JSONObject resources) {
        return new ResponseEntity(tServiceproviderManagerService.resetpassword(resources), HttpStatus.CREATED);
    }

    @Log("修改企业邀请码TServiceproviderManager")
    @RequestMapping(value = "/resetinvitecode")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_CREATE')")
    public ResponseEntity resetinviteCode(@RequestBody JSONObject resources) {
        Long id = SecurityUtils.getOwnerId() ;
        //String inviteCode = resources.getString("inviteCode");
        String inviteCode = tServiceproviderInfoService.resetInviteCode(id, "") ;
        return  HttpResponseUtils.passDefaultResponse(inviteCode, HttpStatus.OK);
    }


    @Log("获取短信验证码")
    @GetMapping(value = "/captcha")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_SELECT')")
    public ResponseEntity getSms(@RequestParam String cellphone) {
        String num = VerifyCodeUtils.generateRandomNum(4);
        if (smsSerivice.sendSms(cellphone, num)) {
            redisService.ttl("sms_" + cellphone, num, 60 * 5);  //设置值,有效期60*5秒
            return HttpResponseUtils.passDefaultResponse("OK", HttpStatus.OK);
        } else {
            return HttpResponseUtils.passDefaultResponse("发送验证码失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 验证密码
     *
     * @param obj
     * @return
     */
    @Log("服务商管理人员修改密码")
    @PostMapping(value = "/changepassword")
    public ResponseEntity changepassword(@Validated @RequestBody JSONObject obj) {
        String originPassword = obj.getString("originPassword");
        String newPassword = obj.getString("password");
        if(StringUtils.isEmpty(originPassword) || StringUtils.isEmpty(newPassword)) {
            return HttpResponseUtils.passDefaultResponse("密码不能为空", HttpStatus.BAD_REQUEST);
        }
        // 返回 token
        return ResponseEntity.ok(tServiceproviderManagerService.changePassword(originPassword, newPassword, SecurityUtils.getUserId()));
    }

    /**
     * 验证密码
     *
     * @param authorizationUser
     * @return
     */
    @Log("服务商管理人员登录")
    @PostMapping(value = "/login")
    public ResponseEntity login(@Validated @RequestBody AuthorizationUser authorizationUser) {
        /*
        // 查询验证码
        String code = redisService.getCodeVal(authorizationUser.getUuid());
        // 清除验证码
        redisService.delete(authorizationUser.getUuid());
        if (StringUtils.isBlank(code)) {
            throw new BadRequestException("验证码已过期");
        }
        if (StringUtils.isBlank(authorizationUser.getCode()) || !authorizationUser.getCode().equalsIgnoreCase(code)) {
            throw new BadRequestException("验证码错误");
        }*/
        final JwtUser jwtUser = (JwtUser) userDetailsService.loadUserByUsername(authorizationUser.getUsername());

        //if(!jwtUser.getPassword().equals(EncryptUtils.encryptPassword(authorizationUser.getPassword()))){
        if (!jwtUser.getPassword().equals(authorizationUser.getPassword())) {
            throw new AccountExpiredException("密码错误");
        }

        if (!jwtUser.isEnabled()) {
            throw new AccountExpiredException("账号已停用，请联系管理员");
        }

        TServiceproviderInfoDTO infoDTO = tServiceproviderInfoService.findById(jwtUser.getOwnerId());
        if(infoDTO.getState() != EnumAuditStatus.ENUM_AUDIT_STATUS_AUDITED.getValue().intValue()) {
            throw new AccountExpiredException("企业信息未通过审核");
        }

        // 生成令牌
        final String token = jwtTokenUtil.generateToken(jwtUser);

        TServiceproviderInfoDTO serviceproviderInfoDTO = tServiceproviderInfoService.findById(jwtUser.getOwnerId()); //归属企业
        cn.hutool.json.JSONObject object = new cn.hutool.json.JSONObject();
        object.put("companyName", serviceproviderInfoDTO.getCompanyItemName());
        object.put("address", serviceproviderInfoDTO.getAddress());

        // 返回 token
        return ResponseEntity.ok(new AuthenticationInfoEx(token, jwtUser, object));
    }

    @Log("获取服务商及个人信息")
    @GetMapping(value = "/info")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_SELECT')")
    public ResponseEntity getServiceproviderManagerInfo() {

        final JwtUser jwtUser = (JwtUser) userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
        TServiceproviderInfoDTO serviceproviderInfoDTO = tServiceproviderInfoService.findById(jwtUser.getOwnerId()); //归属企业

        JSONObject obj = JSON.parseObject(JSONObject.toJSONString(serviceproviderInfoDTO));
        return ResponseEntity.ok(obj);
    }

    @Log("查询服务商已有的全部工单")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERORDER_ALL','TSERVICEPROVIDERORDER_SELECT')")
    @GetMapping(value = "/workorder")
    public ResponseEntity getTWorkOrders(@Nullable TWorkOrderQueryCriteria criteria, Pageable pageable){
        Long serviceproviderid = SecurityUtils.getOwnerId(); //供应商id
        criteria.setSupplier(serviceproviderid);
        Integer status = criteria.getStatus() ;

        //已接收全部工单
        TWorkOrderQueryCriteriaEx criteriaEx = new TWorkOrderQueryCriteriaEx();
        BeanUtils.copyProperties(criteria, criteriaEx, "status");
        List<Integer> statusEx = new ArrayList<>();

        if(status != null) {
            statusEx.add(status);
        } else {
            statusEx.add(EnumWorkorderStatus.DISPATCHED.getValue());
            statusEx.add(EnumWorkorderStatus.DENY.getValue());
            statusEx.add(EnumWorkorderStatus.ACCEPTED.getValue());
            statusEx.add(EnumWorkorderStatus.BACK.getValue());
            statusEx.add(EnumWorkorderStatus.ARRIVED.getValue());
            statusEx.add(EnumWorkorderStatus.FINISHED.getValue());
            statusEx.add(EnumWorkorderStatus.PROCESSING.getValue());
            statusEx.add(EnumWorkorderStatus.EVAlUATED.getValue());
            statusEx.add(EnumWorkorderStatus.CLOSED.getValue());
        }
        return new ResponseEntity(tWorkOrderService.queryAll(criteriaEx, pageable), HttpStatus.OK);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Log("服务商查询TWorkOrderlog")
    @GetMapping(value = "/workorderlog")
    public ResponseEntity getTWorkOrderLogs(@Nullable TWorkOrderLogQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(tWorkOrderLogService.queryAll(criteria,pageable), HttpStatus.OK);
    }

    @Log("查询服务商对应的合同")
    @GetMapping(value = "/tServiceproviderContract")
    public ResponseEntity getTServiceproviderContracts(TServiceproviderContractQueryCriteria criteria, Pageable pageable){
        Long serviceproviderid = SecurityUtils.getOwnerId(); //供应商id
        criteria.setServiceproviderId(serviceproviderid); //供应商
        try {
            return new ResponseEntity(tServiceproviderContractService.queryAll(criteria, pageable), HttpStatus.OK);
        }catch(Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse(ex.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Log("增加企业客户普通管理员")
    @PostMapping(value = "/addmanager")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_CREATE')")
    public ResponseEntity addmanager(@RequestBody JSONObject obj) {
        Long id = SecurityUtils.getUserId();
        TServiceproviderManagerDTO manager = tServiceproviderManagerService.findById(id);
        if(manager.getIsManager() == 0) {
            return HttpResponseUtils.passDefaultResponse("权限不足", HttpStatus.BAD_REQUEST);
        }
        Long serviceproviderid = SecurityUtils.getOwnerId(); //供应商id
        TServiceproviderManager resources = new TServiceproviderManager();
        resources.setServiceproviderId(serviceproviderid);
        resources.setName(obj.getString("name"));
        resources.setCellphone(obj.getString("cellphone"));
        resources.setUsername(obj.getString("username"));
        resources.setIsManager(0); //常规管理员
        resources.setPassword(EncryptUtils.encryptPassword("123456"));

        return new ResponseEntity(tServiceproviderManagerService.create(resources), HttpStatus.CREATED);
    }

    @Log("修改TServiceproviderManager")
    @PostMapping(value = "/updatemanager")
    //@PreAuthorize("hasAnyRole('ADMIN','TServiceproviderManager_ALL','TServiceproviderManager_EDIT')")
    public ResponseEntity updateManager(@Validated @RequestBody TServiceproviderManager resources){
        tServiceproviderManagerService.update(resources);
        return new ResponseEntity(HttpStatus.OK);
    }

    @Log("删除TServiceproviderManager")
    @RequestMapping(value = "/deletemanager/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN','TServiceproviderManager_ALL','TServiceproviderManager_DELETE')")
    public ResponseEntity deleteManager(@PathVariable Long id) {
        try {
            tServiceproviderManagerService.delete(id);
            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse(ex);
        }
    }

    @Log("增加企业客户普通管理员")
    @PostMapping(value = "/addengineer")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_CREATE')")
    public ResponseEntity addengineer( @RequestBody TServiceproviderPerson resources) {
        Long serviceproviderid = SecurityUtils.getOwnerId(); //供应商id
        resources.setServiceproviderId(serviceproviderid);
        resources.setIsManager(0);  //非管理员
        resources.setIsDelete(0);  //非删除
        if(StringUtils.isEmpty(resources.getAccount())) {
            resources.setAccount(resources.getPhone());
        }
        resources.setPersonPassword(EncryptUtils.encryptPassword("123456"));
        /*
        TServiceproviderPerson resources  = new TServiceproviderPerson();
        resources.setServiceproviderId(serviceproviderid);
        //resources.setServiceproviderName(serviceproviderInfoDTO.getSeproName()); //公司名称,service里面设置
        resources.setPersonName(obj.getString("personName"));
        resources.setPhone(obj.getString("phone"));
        resources.setAccount(resources.getPhone());
        resources.setPersonPassword(obj.getString("personPassword"));
        resources.setMajor(obj.getString("major"));
        resources.setLevel(obj.getString("level"));
        resources.setCountry(obj.getString("country"));
        resources.setProvince(obj.getString("province"));
        resources.setCity(obj.getString("city"));
        resources.setCounty(obj.getString("county"));
        resources.setIsManager(0); //常规管理员
        resources.setCreatTime(new Timestamp(System.currentTimeMillis())); */

        return new ResponseEntity(tServiceproviderPersonService.create(resources), HttpStatus.CREATED);
    }

    @Log("增加企业客户普通管理员")
    @PostMapping(value = "/batch")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_CREATE')")
    public ResponseEntity batchAdd(HttpServletRequest request,
                                   @RequestParam MultipartFile file,
                                   @RequestParam String type) {

        InputStream inputStream = null;
        Workbook workbook = null;
        try {
            inputStream = file.getInputStream();
            String xlsx = "xlsx";
            String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
            if (suffix.equals(xlsx)) {
                workbook = new XSSFWorkbook(inputStream);
            } else {
                workbook = new HSSFWorkbook(inputStream);
            }
            Sheet sheet = workbook.getSheetAt(0);

            int rowNo = 0;
            int flag = 2;

            if(type.equals("manager"))
                return batchAddManager(sheet,xlsx);
            else
                return batchAddEngineer(sheet,xlsx);
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse(ex);
        }
    }

    private ResponseEntity batchAddManager(Sheet sheet,String xlsx) {
        try {
            int rowNo = 0;

            JSONArray array = new JSONArray();
            for (Row row : sheet) {
                rowNo++;
                if (rowNo >= 2) { //第三行开始有数据
                    JSONObject obj = new JSONObject();
                    String name = getCellStringValue(row.getCell(0), xlsx);
                    String cellphone = getCellStringValue(row.getCell(1), xlsx);

                    if(StringUtils.isEmpty(name) && StringUtils.isEmpty(cellphone)) {
                        continue;
                    } else {
                        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(cellphone)) {
                            return HttpResponseUtils.passDefaultResponse(String.format("第%d行,手机或姓名不能为空",rowNo),HttpStatus.BAD_REQUEST);
                        }
                    }
                    try {
                        TServiceproviderManagerDTO manager = tServiceproviderManagerService.findByCellphone(cellphone.trim());
                        if(manager != null) {
                            return HttpResponseUtils.passDefaultResponse(String.format("第%d行,手机号码已存在",rowNo),HttpStatus.BAD_REQUEST);
                        }
                    }catch(Exception e) {

                    }

                    obj.put("name", name);
                    obj.put("cellphone", cellphone);
                    Long serviceproviderid = SecurityUtils.getOwnerId(); //供应商id
                    obj.put("serviceproviderId",serviceproviderid);
                    array.add(obj);
                }
            }
            if(array.size() > 0) {
                tServiceproviderManagerService.batchCreate(array);
            }
            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse(ex);
        }
    }

    private ResponseEntity batchAddEngineer(Sheet sheet,String xlsx) {
        try {
            int rowNo = 0;

            java.util.List<TServiceproviderPerson> personList = new ArrayList<>();
            for (Row row : sheet) {
                rowNo++;
                if (rowNo >= 2) { //第三行开始有数据

                    String name = getCellStringValue(row.getCell(0), xlsx);
                    String cellphone = getCellStringValue(row.getCell(1), xlsx);
                    String province = getCellStringValue(row.getCell(2), xlsx);
                    String city = getCellStringValue(row.getCell(3), xlsx);
                    String county = getCellStringValue(row.getCell(4), xlsx);
                    String major = getCellStringValue(row.getCell(5), xlsx);
                    String level = getCellStringValue(row.getCell(6), xlsx);

                    if(StringUtils.isEmpty(name) &&
                            StringUtils.isEmpty(cellphone) &&
                            StringUtils.isEmpty(province) &&
                            StringUtils.isEmpty(city) &&
                            StringUtils.isEmpty(county) &&
                            StringUtils.isEmpty(major) &&
                            StringUtils.isEmpty(level) ) {
                        continue;
                    } else {
                        if(StringUtils.isEmpty(name) ||
                                StringUtils.isEmpty(cellphone) ||
                                StringUtils.isEmpty(province) ||
                                StringUtils.isEmpty(city) ||
                                StringUtils.isEmpty(county) ||
                                StringUtils.isEmpty(major) ||
                                StringUtils.isEmpty(level) ) {
                            return HttpResponseUtils.passDefaultResponse(String.format("第%d行,字段信息不能为空",rowNo),HttpStatus.BAD_REQUEST);
                        }
                    }
                    try{
                        TServiceproviderPersonDTO dto = tServiceproviderPersonService.findByPhone(cellphone);
                        if(dto != null) {
                            return HttpResponseUtils.passDefaultResponse(String.format("第%d行,手机号码已存在",rowNo),HttpStatus.BAD_REQUEST);
                        }
                    }catch(Exception e){

                    }
                    TServiceproviderPerson person = new TServiceproviderPerson();

                    person.setPersonName(name);
                    person.setAccount(cellphone);
                    person.setPhone(cellphone);
                    person.setServiceproviderId(SecurityUtils.getOwnerId());
                    person.setIsManager(0);
                    person.setIsDelete(0);
                    person.setCountry("中国");
                    person.setProvince(province);
                    person.setCity(city);
                    person.setCounty(county);
                    person.setMajor(major);
                    person.setLevel(level);

                    person.setPersonPassword(EncryptUtils.encryptPassword("123456"));
                    personList.add(person);

                }
                if(personList.size() > 0) {
                    tServiceproviderPersonService.batchCreate(personList);
                }
            }
            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse(ex);
        }
    }


    @Log("删除TServiceproviderPerson")
    @DeleteMapping(value = "/delengineer/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_DELETE')")
    public ResponseEntity deleteEngineer(@PathVariable Long id) {
        try {
            tServiceproviderPersonService.delete(id);
            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse(ex);
        }
    }

    @Log("验证企业社会信用码")
    @GetMapping(value = "/verify/{code}")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_DELETE')")
    public ResponseEntity verifyCode(@PathVariable String code) {
        JSONObject obj = new JSONObject();
        obj.put("flag",1);
        try {
            TServiceproviderInfoDTO info = tServiceproviderInfoService.findBySeproCode(code);
            if(info == null) {
                obj.put("flag", 0);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ResponseEntity(obj, HttpStatus.OK);
    }

    @Log("修改TServiceproviderPerson")
    @PostMapping(value = "/updateengineer")
    //@PreAuthorize("hasAnyRole('ADMIN','TSERVICEPROVIDERPERSON_ALL','TSERVICEPROVIDERPERSON_EDIT')")
    public ResponseEntity updateEngineer(@Validated @RequestBody TServiceproviderPerson resources){
        try {
            resources.setIsDelete(0);  //非删除
            tServiceproviderPersonService.update(resources);
            return new ResponseEntity(HttpStatus.OK);
        }catch(Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse(ex);
        }
    }


    @Log("根据name查询字典")
    @GetMapping(value = "/dict/byName/{name}")
    //@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_SELECT')")
    public ResponseEntity getDictsByNmae(@PathVariable String  name){
        return new ResponseEntity(dictService.findByName(name), HttpStatus.OK);
    }

    @Log("根据name查询字典")
    @GetMapping(value = "/dictDetail/findByDeptId/{id}")
    //@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_SELECT')")
    public ResponseEntity findByDeptId(@PathVariable int  id){
        return new ResponseEntity(dictDetailService.findByDeptId(id), HttpStatus.OK);
    }


    @Log("查询字典详情")
    @GetMapping(value = "/dictDetail")
    public ResponseEntity getDictDetails(DictDetailQueryCriteria criteria,
                                         @PageableDefault(value = 10, sort = {"sort"}, direction = Sort.Direction.ASC) Pageable pageable){
        return new ResponseEntity(dictDetailService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @Log("上传图片")
    //@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_UPLOAD')")
    @PostMapping(value = "/pictures")
    @ResponseBody
    public ResponseEntity upload(HttpServletRequest request,@RequestParam MultipartFile file){
        String picture = pictureService.upload(file);
        Map map = new HashMap();
        map.put("errno",0);
        //map.put("id",picture.getId());
        map.put("data",new String[]{picture});
        return new ResponseEntity(map,HttpStatus.OK);
    }


    /**
     * 删除图片
     * @param uid
     * @return
     */
    @Log("删除图片")
    //@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')")
    @DeleteMapping(value = "/pictures/{uid:.+}")
    @ResponseBody
    public ResponseEntity deleteByUid(@PathVariable String uid) {
        try {
            //String ap = ResourceUtils.getFile("classpath:").getAbsolutePath();
            //File f = new File(ap + "/upload/");
            String filePath = uploadFolder+"/" + uid;
            FileUtil.deleteFile(new File(filePath));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    @Log("查询图片")
    //@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_SELECT')")
    @GetMapping(value = "/picture/{uid:.+}")
    public void getPic(@PathVariable String uid,HttpServletResponse response){
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + uid);
        File file;
        FileInputStream fileIn = null;
        ServletOutputStream out = null;
        try {
            String filePath = uploadFolder+"/" + uid;
            file = new File(filePath);
            fileIn = new FileInputStream(file);
            out = response.getOutputStream();
            byte[] outputByte = new byte[1024];
            int readTmp = 0;
            while ((readTmp = fileIn.read(outputByte)) != -1) {
                out.write(outputByte, 0, readTmp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileIn.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Log("查询TEqpttype")
    @GetMapping(value = "/tEqpttype")
    public ResponseEntity getTEqpttypes(TEqpttypeQueryCriteria criteria, Pageable pageable){
        try {
            return new ResponseEntity(tEqpttypeService.queryAll(criteria, pageable), HttpStatus.OK);
        }catch(Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse(ex.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @Log("查询TRegion")
    @GetMapping(value = "/tRegion")
    public ResponseEntity getTRegions(TRegionQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity(tRegionService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    private String getCellStringValue(Object obj, String xlsx) {
        if (obj == null)
            return "";
        Cell cell = null;
        if (xlsx.equals("xlsx")) {
            cell = (XSSFCell) obj;
        } else {
            cell = (HSSFCell) obj;
        }
        switch (cell.getCellTypeEnum()) {
            case FORMULA:
                return cell.getCellFormula();
            case NUMERIC:
                if(org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)){
                    Date date = cell.getDateCellValue();
                    return date.toString();
                }else {
                    DecimalFormat decimalFormat = new DecimalFormat("#");
                    return decimalFormat.format(cell.getNumericCellValue());
                }
            default:
                return cell.getStringCellValue().trim();
        }
    }
}